package com.book.controller;

import com.book.auth.service.LoginService;
import com.book.core.domain.SysUser;
import com.book.core.dto.LoginDTO;
import com.book.core.mode.R;
import com.book.service.SysUserService;
import com.wf.captcha.SpecCaptcha;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@Slf4j
public class SysLoginController {
    private final LoginService loginService;
    private final String KEY_PREFIX = "login-key:";
    private final RedisTemplate<String, String> redisTemplate;
    private final SysUserService sysUserService;
    @PostMapping("/system/login")
    public R userLogin(@RequestBody @Validated LoginDTO loginDTO) {
        //验证验证码的正确性
        String path = KEY_PREFIX + loginDTO.getCaptchaKey();
        String s = redisTemplate.opsForValue().get(path);
        if (s == null || !s.equalsIgnoreCase(loginDTO.getCaptchaValue())) {
            return R.err("验证码错误!");
        }
        Map<String, Object> map = loginService.login(loginDTO);
        return R.ok("登录成功", map);
    }
    @PostMapping("/system/register")
    public R<String> register(@RequestBody @Validated SysUser user) {
        sysUserService.createSysUser(user);
        return R.ok("注册成功",null);
    }

    @PostMapping("/system/logout")
    public R<String> logout() {
        System.out.println("进入人方法");
        loginService.logout();
        return R.ok("注销成功",null);
    }
    @RequestMapping("/captcha")
    public R<Map<String, String>> loginCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        String path = KEY_PREFIX + key;
        // 存入redis并设置过期时间为3分钟
        redisTemplate.opsForValue().set(path, verCode, 3, TimeUnit.MINUTES);
        HashMap<String, String> map = new HashMap<>();
        map.put("captchaKey", key);
        map.put("captchaImage", specCaptcha.toBase64());
        log.info("验证码key为：code:{},验证码值为：value:{}", key, verCode);
        // 将key和base64返回给前端
        return R.ok(map);
    }
}
